﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Reflection;
using ArtMath.Setting;
using ArtMath.Component;
using ArtMath.Resource;
using ArtMath.Command;
using ArtMath.Window.Interface;
using ArtMath.Flag;
using ArtMath.Component.Annotation;
using ArtMath.Control;
using ArtMath.Core.Helper;
using ArtMath.Core.Data;
using System.Text;
using ArtMath.AuxiliaryTool;
using System.Collections.Generic;
using System.ComponentModel;
using ArtMath.Interaction.Interface;
using System.Drawing.Printing;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Net;
using System.Runtime.InteropServices;
using ArtMath.CommonType;

namespace ArtMath.Window
{
    public partial class MainWindow : Form, ISwitchLanguage, IStatusMessage
    {
        public class InitializationData
        {
            public ToolStripItem[] ConstructionMenuItems, MeasureMenuItems;
            public List<ToolStripItem> RecentDocumentMenuItems;
        }
        [Browsable(false)]
        public SketchPad LinkedPad { get; private set; }
        [Browsable(false)]
        public Document LinkedDocument { get; private set; }
        Dictionary<ToolStripMenuItem, DocumentWindow> documentWindows = new Dictionary<ToolStripMenuItem, DocumentWindow>();
        WelcomeWindow welcomeWin;
        public MainWindow(InitializationData initData)
        {
            InitializeComponent();
            tsslCoordinate.Alignment = ToolStripItemAlignment.Right;
            构造CToolStripMenuItem.DropDownItems.AddRange(initData.ConstructionMenuItems);
            度量MToolStripMenuItem.DropDownItems.AddRange(initData.MeasureMenuItems);
            CustomSwitchLanguage();
            ToolStripMenuItem[] langMenus = new ToolStripMenuItem[] { 简体中文ToolStripMenuItem, englishToolStripMenuItem };
            foreach (ToolStripMenuItem item in langMenus)
            {
                if (item.Tag as string == Settings.Instance.Language)
                {
                    item.Checked = true;
                }
                item.CheckedChanged += (object sender, EventArgs e) =>
                {
                    ToolStripMenuItem tsmi = sender as ToolStripMenuItem;
                    if (tsmi.Checked)
                    {
                        foreach (ToolStripMenuItem menu in langMenus)
                        {
                            if (ReferenceEquals(menu, sender)) continue;
                            menu.Checked = false;
                        }
                        Settings.Instance.Language = tsmi.Tag as string;
                        MessageBox.Show(Resources.Translate("RestartAfterSwitchLanguage"), Resources.Translate("Prompt"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        bool hasCheck = false;
                        foreach (ToolStripMenuItem menu in langMenus)
                        {
                            if (menu.Checked)
                            {
                                hasCheck = true;
                                break;
                            }
                        }
                        if (!hasCheck)
                        {
                            tsmi.Checked = true;
                        }
                    }
                };
            }
            Program.WinAnimations.AnimationStateChanged += (bool containsRunning) =>
            {
                if (containsRunning)
                {
                    tsbMoveObjects.Enabled = tsbMoveObjects.Checked = false;
                }
                else
                {
                    tsbMoveObjects.Enabled = true;
                }
            };
            foreach (ToolStripItem item in initData.RecentDocumentMenuItems)
            {
                最近打开的文档ToolStripMenuItem.DropDownItems.Add(item);
                item.Click += RecentItem_Click;
            }
            最近打开的文档ToolStripMenuItem.Enabled = 最近打开的文档ToolStripMenuItem.DropDownItems.Count > 0;
            ChangeColorTheme(Settings.Instance.ColorTheme);
        }
        public void RecentItem_Click(object sender, EventArgs e)
        {
            ToolStripItem item = sender as ToolStripItem;
            Tuple<string, string> tup = item.Tag as Tuple<string, string>;
            if (File.Exists(tup.Item2))
            {
                Program.WinDocuments.OpenDocument(tup.Item2);
            }
            else
            {
                if (MessageBox.Show(string.Format(Resources.Translate("FileNotExist"), tup.Item2) + Resources.FullStop + Resources.Translate("RemoveAsk"), Resources.Translate("Ask"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    RemoveRecentItem(item);
                    UserOptions.Instance.Remove(tup);
                }
            }
        }
        public void RemoveRecentItem(Tuple<string, string> tup)
        {
            ToolStripItemCollection col = 最近打开的文档ToolStripMenuItem.DropDownItems;
            foreach (ToolStripItem item in col)
            {
                if (item.Tag.Equals(tup))
                {
                    RemoveRecentItem(item);
                    break;
                }
            }
        }
        public void RemoveRecentItem(ToolStripItem item)
        {
            ToolStripItemCollection col = 最近打开的文档ToolStripMenuItem.DropDownItems;
            int index = col.IndexOf(item);
            for (int i = index + 1; i < col.Count; i++)
            {
                col[i].Text = "&" + (i - 1) + col[i].Text.Substring(2);
            }
            col.Remove(item);
            最近打开的文档ToolStripMenuItem.Enabled = col.Count > 0;
        }
        public void ChangeColorTheme(UIColorTheme theme)
        {
            //string tmpFile = Path.Combine(Path.GetTempPath(), "DockPanel.temp.config");
            //dockPanel1.SaveAsXml(tmpFile);
            //closeAllContents();
            switch (theme)
            {
                case UIColorTheme.Light:
                    dockPanel1.Theme = vS2015LightTheme1;
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015LightTheme1);
                    break;
                case UIColorTheme.Blue:
                    dockPanel1.Theme = vS2015BlueTheme1;
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015BlueTheme1);
                    break;
                case UIColorTheme.Dark:
                    dockPanel1.Theme = vS2015DarkTheme1;
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015DarkTheme1);
                    break;
            }
            if (dockPanel1.Theme.ColorPalette != null)
            {
                statusStrip1.BackColor = dockPanel1.Theme.ColorPalette.MainWindowStatusBarDefault.Background;
            }
            //try
            //{
            //    dockPanel1.LoadFromXml(tmpFile, Program.GetContentFromPersistString);
            //    File.Delete(tmpFile);
            //}
            //catch (Exception)
            //{
            //}
        }
        public void SketchPad_Activated(SketchPad sender)
        {
            tsbUndo.DropDownItems.Clear();
            tsbRedo.DropDownItems.Clear();
            tsbScale.Checked = tsbMovePad.Checked = tsbMoveObjects.Checked = tsbTransformPoint.Checked = 
                自由变换TToolStripMenuItem.Checked = false;
            LinkedPad = sender;
            if (LinkedPad == null)
            {
                tsPad.Enabled = /*构造CToolStripMenuItem.Visible = 度量MToolStripMenuItem.Visible =*/
                    新建动画NToolStripMenuItem.Enabled = 清空动画ToolStripMenuItem.Enabled = false;
                foreach (ToolStripItem item in 构造CToolStripMenuItem.DropDownItems)
                {
                    item.Enabled = false;
                }
                foreach (ToolStripItem item in 度量MToolStripMenuItem.DropDownItems)
                {
                    item.Enabled = false;
                }
                if (LinkedDocument == null)
                {
                    Text = Flags.SoftwareName + Flags.AdministratorFlag;
                }
                else
                {
                    Text = $"{LinkedDocument.Title} - {Flags.SoftwareName}{Flags.AdministratorFlag}";
                }
            }
            else
            {
                foreach (ToolStripItem item in 构造CToolStripMenuItem.DropDownItems)
                {
                    item.Enabled = true;
                }
                foreach (ToolStripItem item in 度量MToolStripMenuItem.DropDownItems)
                {
                    item.Enabled = true;
                }
                foreach (ICommand item in LinkedPad.Undos)
                {
                    tsbUndo.DropDownItems.Add(item.UndoMenuItem);
                }
                tsbUndo.Enabled = tsbUndo.DropDownItems.Count > 0;
                foreach (ICommand item in LinkedPad.Redos)
                {
                    tsbRedo.DropDownItems.Add(item.RedoMenuItem);
                }
                tsbRedo.Enabled = tsbRedo.DropDownItems.Count > 0;
                switch (LinkedPad.SelectedToolType)
                {
                    case ToolTypeName.sf:
                        tsbScale.Checked = true;
                        break;
                    case ToolTypeName.ydhb:
                        tsbMovePad.Checked = true;
                        break;
                    case ToolTypeName.yddx:
                        tsbMoveObjects.Checked = true;
                        break;
                    case ToolTypeName.qhdlx:
                        tsbTransformPoint.Checked = true;
                        break;
                    case ToolTypeName.zybh:
                        自由变换TToolStripMenuItem.Checked = true;
                        break;
                }
                tsPad.Enabled = /*构造CToolStripMenuItem.Visible = 度量MToolStripMenuItem.Visible =*/
                    新建动画NToolStripMenuItem.Enabled = 清空动画ToolStripMenuItem.Enabled = true;
                Text = $"{LinkedPad.Document.Title} [{LinkedPad.Name}] - {Flags.SoftwareName}{Flags.AdministratorFlag}";
            }
        }
        public ToolStripButton MoveObjectButton
        {
            get { return tsbMoveObjects; }
        }
        public ToolStripButton MoveSketchPadButton
        {
            get { return tsbMovePad; }
        }
        public ToolStripButton SwitchPointButton
        {
            get { return tsbTransformPoint; }
        }
        public ToolStripButton ScaleButton
        {
            get { return tsbScale; }
        }
        //public ToolStripMenuItem TransformMenu
        //{
        //    get { return 自由变换TToolStripMenuItem; }
        //}
        //public ToolStripSplitButton UndoButton
        //{
        //    get { return tsbUndo; }
        //}
        //public ToolStripSplitButton RedoButton
        //{
        //    get { return tsbRedo; }
        //}
        public ToolStripMenuItem WindowTopMenu
        {
            get { return 窗口WToolStripMenuItem1; }
        }
        public ToolStripMenuItem DocumentManagerMenu
        {
            get { return 文档管理器ToolStripMenuItem; }
        }
        public ToolStripMenuItem ToolBoxMenu
        {
            get { return 工具箱ToolStripMenuItem; }
        }
        public ToolStripMenuItem ParameterManagerMenu
        {
            get { return 参数PToolStripMenuItem; }
        }
        public ToolStripMenuItem ComponentManagerMenu
        {
            get { return 元件管理器ToolStripMenuItem; }
        }
        public ToolStripMenuItem PropertyMenu
        {
            get { return 属性ToolStripMenuItem; }
        }
        public ToolStripMenuItem AnimationManagerMenu
        {
            get { return 动画管理器ToolStripMenuItem; }
        }
        public ToolStripMenuItem CommandMenu
        {
            get { return 控制台ToolStripMenuItem; }
        }
        public ToolStripMenuItem RecycleBinMenu
        {
            get { return 回收站ToolStripMenuItem; }
        }
        public ToolStripMenuItem RecentOpenedDocumentMenu
        {
            get { return 最近打开的文档ToolStripMenuItem; }
        }
        private void MainWindow_Load(object sender, EventArgs e)
        {
            try
            {
                dockPanel1.LoadFromXml(Flags.DefaultLayoutPath, Program.GetContentFromPersistString);
            }
            catch (Exception)
            {
                Program.LoadDefaultLayout(dockPanel1);
            }
            if (Directory.Exists(Flags.LayoutDirectoryPath))
            {
                try
                {
                    DirectoryInfo di = new DirectoryInfo(Flags.LayoutDirectoryPath);
                    int index = 0;
                    foreach (FileInfo item in di.GetFiles("*.config"))
                    {
                        ToolStripMenuItem menu = new ToolStripMenuItem($"&{'A'.GetNextLetter(index++)}. {item.Name.Split('.')[0]}", null, LoadLayout_Click) { Tag = item.FullName };
                        加载窗口布局LToolStripMenuItem.DropDownItems.Add(menu);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                //Program.DoAdmin(new MessageContent());
            }
            if (Program.OpenFiles?.Length > 0)
            {
                Program.WinDocuments.OpenDocuments(Program.OpenFiles);
            }
            else
            {
                if (Settings.Instance.ShowHomePageAfterStartup)
                {
                    welcomeWin = new WelcomeWindow();
                    welcomeWin.Show(dockPanel1, DockState.Document);
                }
            }
            if (UserOptions.Instance.NormalExit)
            {
                UserOptions.Instance.NormalExit = false;
                UserOptions.Instance.Save();
            }
            else
            {
                if (UserOptions.Instance.AutoSaveNewestPath.Count > 0)
                {
                    DocumentRecoverWindow dr = new DocumentRecoverWindow();
                    if (dr.ShowDialog() == DialogResult.OK)
                    {

                    }
                }
            }
            if (Settings.Instance.CheckExtension)
            {
                try
                {
                    if (!Flags.GetExtensionRegistered() || Flags.GetExtensionExecutablePath() != Application.ExecutablePath)
                    {
                        CheckFileExtensionWindow cfe = new CheckFileExtensionWindow();
                        if (cfe.ShowDialog() == DialogResult.Yes)
                        {
                            //if (File.Exists(Flags.FileAssociationProgramPath))
                            //{
                            //    Process.Start(Flags.FileAssociationProgramPath);
                            //}
                            //else
                            //{
                            //    MessageBox.Show(Resources.Translate("FileAssociationProgramNotExist"), Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                            //    Settings.Instance.CheckExtension = false;
                            //}
                            try
                            {
                                Flags.RegisterExtension();
                                Console.WriteLine(Resources.Translate("Complete"));
                            }
                            catch (UnauthorizedAccessException)
                            {
                                MessageBox.Show(Resources.Translate("ExtensionRegisterFailed_Unauthorized"), Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            catch (SecurityException)
                            {
                                MessageBox.Show(Resources.Translate("ExtensionRegisterFailed_Unauthorized"), Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            catch (Exception)
                            {
                                MessageBox.Show(Resources.Translate("ExtensionRegisterFailed"), Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                                Settings.Instance.CheckExtension = false;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show(Resources.Translate("ExtensionRegisterFailed"), Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Settings.Instance.CheckExtension = false;
                }
            }
            tsslMainStatus.Text = Resources.Translate("Ready");
        }
        //ListViewItem[] getRecoverItems()
        //{
        //    List<ListViewItem> items = new List<ListViewItem>();
        //    Dictionary<string, List<FileInfo>> cat = new Dictionary<string, List<FileInfo>>();
        //    DirectoryInfo di = new DirectoryInfo(Flags.TempFolder);
        //    foreach (FileInfo fi in di.GetFiles("*" + Flags.TempDocumentSuffix, SearchOption.TopDirectoryOnly))
        //    {
        //        string[] tokens = fi.Name.Split(' ');
        //        if (tokens.Length != 3) continue;
        //        if (cat.ContainsKey(tokens[0]))
        //        {
        //            cat[tokens[0]].Add(fi);
        //        }
        //        else
        //        {
        //            cat.Add(tokens[0], new List<FileInfo>() { fi });
        //        }
        //    }
        //    object[] objs;
        //    FileStream stream;
        //    IFormatter fmt = new BinaryFormatter();
        //    foreach (KeyValuePair<string, List<FileInfo>> item in cat)
        //    {
        //        item.Value.Sort((FileInfo x, FileInfo y) => { return y.LastWriteTime.CompareTo(x.LastWriteTime); });
        //        try
        //        {
        //            stream = new FileStream(item.Value[0].FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        //            objs = fmt.Deserialize(stream) as object[];
        //            stream.Close();
        //        }
        //        catch (Exception)
        //        {
        //            continue;
        //        }
        //        Document doc = objs[0] as Document;
        //        if (doc == null) continue;
        //        ListViewItem lvitem = new ListViewItem(item.Key) { Tag = item.Value };
        //        lvitem.SubItems.Add(doc.LinkedFile != null ? doc.LinkedFile.Name : string.Empty);
        //        items.Add(lvitem);
        //    }
        //    return items.ToArray();
        //}
        private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                if (!Flags.ASCsuccess) Flags.Ctrl = true;
                if (e.KeyCode == Keys.N)
                {
                    if (Program.WinDocuments.DocumentList.SelectedItems.Count == 0)
                    {
                        Program.WinDocuments.AddDocument();
                    }
                    else
                    {
                        Program.WinDocuments.AddSketchpad();
                    }
                }
            }
            else if (e.Shift)
            {
                if (!Flags.ASCsuccess) Flags.Shift = true;
                if (tsbScale.Checked)
                {
                    if (LinkedPad != null)
                    {
                        LinkedPad.Canvas.Cursor = new Cursor(Resource.Properties.Resources.zoom_out.GetHicon());
                    }
                }
            }
            else if (e.Alt)
            {
                if (!Flags.ASCsuccess) Flags.Alt = true;
            }
            else
            {
                switch (e.KeyCode)
                {
                    case Keys.Escape:
                        if (LinkedPad.SuspendCreation())
                        {
                            ShowMainStatus(Resources.Translate("Ready"));
                            ClearSecondaryStatus();
                        }
                        break;
                }
            }
        }
        private void MainWindow_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.ControlKey:
                    if (!Flags.ASCsuccess) Flags.Ctrl = false;
                    break;
                case Keys.ShiftKey:
                    if (!Flags.ASCsuccess) Flags.Shift = false;
                    if (LinkedPad != null)
                    {
                        if (tsbScale.Checked)
                        {
                            LinkedPad.Canvas.Cursor = new Cursor(Resource.Properties.Resources.zoom_in.GetHicon());
                        }
                    }
                    break;
            }
        }
        private void tsbCapture_Click(object sender, EventArgs e)
        {
            captureToFile();
        }
        void captureToFile()
        {
            ShowMainStatus($"{Resources.Translate("Rendering")}...");
            Bitmap bmp = LinkedPad.GetThumbNail();
            ShowMainStatus(Resources.Translate("RenderComplete"));
            sfd.Filter = $"{Resources.Translate("bmp")}(*.bmp)|*.bmp|{Resources.Translate("jpg")}(*.jpg, *.jpeg)|*.jpg;*.jpeg|{Resources.Translate("png")}(*.png)|*.png|{Resources.Translate("wmf")}(*.wmf)|*.wmf";
            sfd.FileName = string.Empty;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                ImageFormat Format = ImageFormat.Bmp;
                switch (sfd.FilterIndex)
                {
                    case 0:
                        Format = ImageFormat.Bmp;
                        break;
                    case 1:
                        Format = ImageFormat.Jpeg;
                        break;
                    case 2:
                        Format = ImageFormat.Png;
                        break;
                    case 3:
                        Format = ImageFormat.Wmf;
                        break;
                }
                try
                {
                    bmp.Save(sfd.FileName, Format);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            ShowMainStatus(Resources.Translate("Ready"));
        }
        private void tsbRefresh_Click(object sender, EventArgs e)
        {
            LinkedPad.Canvas.Refresh();
            Program.WinProperty.SketchPad_RefreshMenuClick(LinkedPad);
        }
        private void tsbMagnet_Click(object sender, EventArgs e)
        {
            switch (LinkedPad.PointAbsorbMode)
            {
                case PointAbsorb.No:
                    tsbMagnet.Image = Resource.Properties.Resources.magnet_plus;
                    tsbMagnet.Text = Resources.JoinLocalizedString("Auto", "Absorb");
                    LinkedPad.PointAbsorbMode = PointAbsorb.Auto;
                    break;
                case PointAbsorb.Ask:
                    tsbMagnet.Image = Resource.Properties.Resources.magnet_minus;
                    tsbMagnet.Text = Resources.JoinLocalizedString("No2", "Absorb");
                    LinkedPad.PointAbsorbMode = PointAbsorb.No;
                    break;
                case PointAbsorb.Auto:
                    tsbMagnet.Image = Resource.Properties.Resources.magnet_pencil;
                    tsbMagnet.Text = Resources.JoinLocalizedString("AskBeforeAbsorb");
                    LinkedPad.PointAbsorbMode = PointAbsorb.Ask;
                    break;
            }
        }
        private void tsbMovePad_CheckedChanged(object sender, EventArgs e)
        {
            if (tsbMovePad.Checked)
            {
                foreach (ListViewItem item in Program.WinTools.ToolList.SelectedItems)
                {
                    item.Selected = false;
                }
                tsbScale.Checked = tsbMoveObjects.Checked = tsbTransformPoint.Checked = 自由变换TToolStripMenuItem.Checked = false;
                LinkedPad.SelectedToolType = ToolTypeName.ydhb;
            }
            else
            {
                LinkedPad.SelectedToolType = ToolTypeName.zz;
            }
            移动画板ToolStripMenuItem.Checked = tsbMovePad.Checked;
        }

        private void tsbScale_CheckedChanged(object sender, EventArgs e)
        {
            if (tsbScale.Checked)
            {
                foreach (ListViewItem item in Program.WinTools.ToolList.SelectedItems)
                {
                    item.Selected = false;
                }
                tsbMovePad.Checked = tsbMoveObjects.Checked = tsbTransformPoint.Checked = 自由变换TToolStripMenuItem.Checked = false;
                LinkedPad.SelectedToolType = ToolTypeName.sf;
            }
            else
            {
                LinkedPad.SelectedToolType = ToolTypeName.zz;
            }
        }
        private void tsbMoveObjects_CheckedChanged(object sender, EventArgs e)
        {
            if (tsbMoveObjects.Checked)
            {
                foreach (ListViewItem item in Program.WinTools.ToolList.SelectedItems)
                {
                    item.Selected = false;
                }
                tsbScale.Checked = tsbMovePad.Checked = tsbTransformPoint.Checked = 自由变换TToolStripMenuItem.Checked = false;
                LinkedPad.SelectedToolType = ToolTypeName.yddx;
            }
            else
            {
                LinkedPad.SelectedToolType = ToolTypeName.zz;
            }
            移动对象ToolStripMenuItem.Checked = tsbMoveObjects.Checked;
        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                Program.WinDocuments.CloseDocument(true);
            }
            catch (OperationCanceledException)
            {
                e.Cancel = true;
                return;
            }
            if (!Program.WinRecycleBin.IsDisposed)
            {
                Program.WinRecycleBin.Close();
            }
            if (Flags.SaveLayoutBeforeExit)
            {
                try
                {
                    dockPanel1.SaveAsXml(Flags.DefaultLayoutPath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"{Resources.Translate("FailSaveWindowLayout")}{Resources.ColonSeparate}{ex.Message}", Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            if (e.CloseReason == CloseReason.UserClosing)
            {
                UserOptions.Instance.NormalExit = true;
                UserOptions.Instance.AutoSaveNewestPath.Clear();
                UserOptions.Instance.Save();
                ShowMainStatus(Resources.Translate("DeletingTempFiles") + "...");
                Flags.DeleteTemporaryFiles(true);
            }
        }

        private void 发送反馈信息FToolStripMenuItem_Click(object sender, EventArgs e)
        {
            switch (MessageBox.Show(string.Format(Resources.Translate("FeedbackAsk"), Environment.NewLine, Flags.FeedbackReceiver), Resources.Translate("Ask"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
            {
                case DialogResult.Yes:
                    try
                    {
                        Process.Start($"mailto:{Flags.FeedbackReceiver}?subject={Flags.SoftwareName}{Resources.Join}{Resources.Translate("Feedback")}");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case DialogResult.No:
                    try
                    {
                        Clipboard.SetText(Flags.FeedbackReceiver);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
            }
        }

        private void tsbZoomIn_Click(object sender, EventArgs e)
        {
            LinkedPad?.ZoomIn(Settings.Instance.ZoomDelta);
        }
        private void 复制CToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinComponents.CopyObject();
        }

        void 粘贴PToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Flags.ShieldCtrl(() =>
            {
                Program.WinComponents.PasteObject(LinkedPad);
            });
        }

        private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinComponents.CutObject();
        }

        private void tsbFullScreen_Click(object sender, EventArgs e)
        {
            if (LinkedPad == null) return;
            LinkedPad.FullScreenMode = true;
        }
        private void 新建画板PToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinDocuments.AddSketchpad();
        }

        private void 关于AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutWindow aw = new AboutWindow();
            aw.ShowDialog();
        }

        private void 文档管理器ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            if (文档管理器ToolStripMenuItem.Checked)
            {
                Program.WinDocuments.Show();
            }
            else
            {
                Program.WinDocuments.Hide();
            }
        }
        public DockPanel MainDockPanel
        {
            get { return dockPanel1; }
        }
        private void 设置SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsWindow sw = new SettingsWindow();
            if (sw.ShowDialog() == DialogResult.OK)
            {

            }
        }
        private void tsbZoomOut_Click(object sender, EventArgs e)
        {
            LinkedPad?.ZoomOut(Settings.Instance.ZoomDelta);
        }
        private void 自由变换TToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            LinkedPad.Canvas.Cursor = Cursors.Default;
            toolStripSeparator11.Visible = tsbSubmit.Visible = tsbCancel.Visible = 自由变换TToolStripMenuItem.Checked;
            if (自由变换TToolStripMenuItem.Checked)
            {
                CustomBase cb = null;
                LinkedPad.ForEachExistVisibleObject((Base obj) =>
                {
                    cb = obj as CustomBase;
                    return cb == null;
                }, false, false);
                if (cb == null)
                {
                    自由变换TToolStripMenuItem.Checked = false;
                }
                else
                {
                    foreach (ListViewItem item in Program.WinTools.ToolList.SelectedItems)
                    {
                        item.Selected = false;
                    }
                    tsbScale.Checked = tsbMovePad.Checked = tsbTransformPoint.Checked = tsbMoveObjects.Checked = false;
                    LinkedPad.SelectedToolType = ToolTypeName.zybh;
                    LinkedPad.SelectNothing();
                    Transform t = new Transform(cb.DrawRegion, cb.RotateCenter.ToPointD(), cb.RotateAngle.RadValue);
                    t.CursorChanged += (Cursor cur) =>
                    {
                        LinkedPad.Canvas.Cursor = cur;
                    };
                    t.RotateCenterChanged += (PointD ct) =>
                    {
                        cb.RotateCenter.SetFromPointD(LinkedPad.PxyToMath(ct));
                    };
                    t.RotateAngleChanged += (double angle) =>
                    {
                        cb.RotateAngle.SetExpression(LinkedPad.ShowRad(angle));
                    };
                    t.LocationChanged += (PointD loc) =>
                    {
                        cb.Location.SetFromPointD(LinkedPad.PxyToMath(loc));
                    };
                    LinkedPad.ToolObj = t;
                }
            }
            else
            {
                LinkedPad.SelectedToolType = ToolTypeName.zz;
                //linkedPad.FunctionTrackObj?.DoEventsAndDispose();
            }
        }

        private void tsbSubmit_Click(object sender, EventArgs e)
        {
            Transform t = LinkedPad.ToolObj as Transform;
            if (t == null) return;
            t.Complete();
        }
        private void tsbUndo_ButtonClick(object sender, EventArgs e)
        {
            LinkedPad.Undo();
        }
        private void tsbRedo_ButtonClick(object sender, EventArgs e)
        {
            LinkedPad.Redo();
        }

        private void 撤销ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tsbUndo_ButtonClick(sender, e);
        }

        private void 重做ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tsbRedo_ButtonClick(sender, e);
        }

        private void tsbUndo_EnabledChanged(object sender, EventArgs e)
        {
            撤销ToolStripMenuItem.Enabled = tsbUndo.Enabled;
        }

        private void tsbRedo_EnabledChanged(object sender, EventArgs e)
        {
            重做ToolStripMenuItem.Enabled = tsbRedo.Enabled;
        }

        private void 水平翻转ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flipObj(PointD.Empty, double.PositiveInfinity);
        }

        private void tsbCancel_Click(object sender, EventArgs e)
        {
            Transform t = LinkedPad.ToolObj as Transform;
            if (t == null) return;
            t.DiscardChanges();
        }

        private void tsbTransformPoint_CheckedChanged(object sender, EventArgs e)
        {
            LinkedPad.Canvas.Cursor = Cursors.Default;
            if (tsbTransformPoint.Checked)
            {
                foreach (ListViewItem item in Program.WinTools.ToolList.SelectedItems)
                {
                    item.Selected = false;
                }
                tsbScale.Checked = tsbMovePad.Checked = tsbMoveObjects.Checked = 自由变换TToolStripMenuItem.Checked = false;
                LinkedPad.SelectedToolType = ToolTypeName.qhdlx;
                LinkedPad.SelectNothing();
            }
            else
            {
                LinkedPad.SelectedToolType = ToolTypeName.zz;
            }
            切换点类型ToolStripMenuItem.Checked = tsbTransformPoint.Checked;
        }
        private void tsmiNewDoc_Click(object sender, EventArgs e)
        {
            Program.WinDocuments.AddDocument();
        }
        private void tsbCaptureToClipboard_Click(object sender, EventArgs e)
        {
            captureToClipboard();
        }
        void captureToClipboard()
        {
            tsslMainStatus.Text = $"{Resources.Translate("Rendering")}...";
            Bitmap bmp = LinkedPad.GetThumbNail();
            tsslMainStatus.Text = $"{Resources.Translate("SetClipboard")}...";
            try
            {
                Clipboard.Clear();
                Clipboard.SetImage(bmp);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            tsslMainStatus.Text = Resources.Translate("Ready");
        }
        private void 工具箱ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            if (工具箱ToolStripMenuItem.Checked)
            {
                Program.WinTools.Show();
            }
            else
            {
                Program.WinTools.Hide();
            }
        }

        private void 参数管理器ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            if (参数管理器ToolStripMenuItem.Checked)
            {
                Program.WinParameters.Show();
            }
            else
            {
                Program.WinParameters.Hide();
            }
        }

        private void 元件管理器ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            if (元件管理器ToolStripMenuItem.Checked)
            {
                Program.WinComponents.Show();
            }
            else
            {
                Program.WinComponents.Hide();
            }
        }

        private void 属性ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            if (属性ToolStripMenuItem.Checked)
            {
                Program.WinProperty.Show();
            }
            else
            {
                Program.WinProperty.Hide();
            }
        }

        private void 动画管理器ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            if (动画管理器ToolStripMenuItem.Checked)
            {
                Program.WinAnimations.Show();
            }
            else
            {
                Program.WinAnimations.Hide();
            }
        }

        private void 回收站ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            if (回收站ToolStripMenuItem.Checked)
            {
                Program.WinRecycleBin.Show();
            }
            else
            {
                Program.WinRecycleBin.Hide();
            }
        }

        private void 浮动FToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinDocuments.Float();
        }

        private void 全部浮动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinDocuments.Float(true);
        }
        public void CustomSwitchLanguage()
        {
            string[] cons = new string[] { Resources.Translate("MidPoint") , Resources.Translate("CrossoverPoint"),
            Resources.JoinLocalizedString("Shape", "Center"),Resources.JoinLocalizedString("Polygon", "BaryCenter"),
                Resources.JoinLocalizedString("Triangle", "CircumCenter"),
                Resources.JoinLocalizedString("Triangle", "InCenter"),
                Resources.JoinLocalizedString("Triangle", "OrthoCenter"), Resources.Translate("DerivedFunction"),
            Resources.Translate("ParallelLine"), Resources.Translate("VerticalLine"),
                Resources.Translate("PerpendicularBisector"), Resources.Translate("VerticalLineSegment"),
                Resources.Translate("TangentLine"),
                Resources.Translate("AngleBisector"),Resources.Translate("TwoVectorsAddition"),
                Resources.Translate("TwoVectorsSubtraction"),Resources.Translate("CircumCircle"), Resources.Translate("InscribedCircle")};
            int offset = 0;
            for (int i = 0; i < cons.Length; i++)
            {
                ToolStripItem item = 构造CToolStripMenuItem.DropDownItems[i + offset];
                if (item is ToolStripSeparator)
                {
                    offset++;
                    i--;
                }
                else
                {
                    item.Text = $"&{'A'.GetNextLetter(i)}. {cons[i]}";
                }
            }
            cons = new string[] { Resources.Translate("TwoPointsDistance"),
                Resources.Translate("PointStraightLineDistance"), Resources.Translate("TwoParallelLinesDistance"),
                Resources.Translate("TwoStraightLinesIncludedAngle"), Resources.Translate("TwoStraightLinesArrivalAngle"),
                Resources.Translate("TwoVectorsScalarProduct"), Resources.Translate("TwoVectorsCrossProduct") };
            offset = 0;
            for (int i = 0; i < cons.Length; i++)
            {
                ToolStripItem item = 度量MToolStripMenuItem.DropDownItems[i + offset];
                if (item is ToolStripSeparator)
                {
                    offset++;
                    i--;
                }
                else
                {
                    item.Text = $"&{'A'.GetNextLetter(i)}. {cons[i]}";
                }
            }
        }
        public void SketchPad_Layer_RefreshWindowsStatus(LayerControl sender, LayerControl.RefreshWindowsStatusEventArgs e)
        {
            全选AToolStripMenuItem.Enabled = 反选RToolStripMenuItem.Enabled = sender.Items.Count((LayerItem item) => { return item.ObjectState == ObjectState.Normal; }) > 0;
            旋转ToolStripMenuItem.Enabled = 翻转FToolStripMenuItem.Enabled = sender.SelectedItems.Count((LayerItem item) => { return item.LinkedObj != null; }) > 0;
        }

        private void 全选AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LinkedPad.SelectAll();
        }

        private void 反选RToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LinkedPad.SelectReverse();
        }

        private void tsbUndo_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            LinkedPad.Undo((ICommand)e.ClickedItem.Tag);
        }

        private void tsbRedo_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            LinkedPad.Redo((ICommand)e.ClickedItem.Tag);
        }
        private void 查找FToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            Program.WinComponents.SearchChecked = 查找FToolStripMenuItem.Checked;
        }

        private void 锁定LToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinComponents.SetLock(true);
        }

        private void 解锁UToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinComponents.SetLock(false);
        }

        private void 清除轨迹ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinComponents.ClearTracks();
        }

        private void 删除DToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinComponents.DeleteComponents();
        }

        private void 清空EToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinComponents.DeleteComponents(true);
        }

        private void 新建参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinParameters.AddParameter();
        }

        private void 删除参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinParameters.DeleteParameters();
        }

        private void 清空参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinParameters.DeleteParameters(true);
        }

        private void 参数自增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinParameters.IncreaseSelectedParameter();
        }

        private void 参数自减ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinParameters.IncreaseSelectedParameter(-1);
        }

        private void 圈数归零ZToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinParameters.ResetRound();
        }

        private void tsmiPrint_Click(object sender, EventArgs e)
        {
            Program.WinDocuments.Print();
        }
        public void NotifyMenuPropertyChanged(string menuName, string propName, object newValue)
        {
            foreach (ToolStripMenuItem top in menuStrip1.Items)
            {
                foreach (ToolStripItem item in top.DropDownItems)
                {
                    ToolStripMenuItem menu = item as ToolStripMenuItem;
                    if (menu == null) continue;
                    if (menu.Name == menuName)
                    {
                        PropertyInfo pi = menu.GetType().GetProperty(propName);
                        pi.SetValue(menu, newValue, null);
                        return;
                    }
                }
            }
        }

        private void 向左旋转90ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rotateObj(Angle.RightAngle);
        }

        private void 向右旋转90ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rotateObj(-Angle.RightAngle);
        }

        private void 向右旋转180ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rotateObj(-Math.PI);
        }
        void rotateObj(double angle)
        {
            foreach (LayerItem item in LinkedPad.Layer.SelectedItems)
            {
                if (item.LinkedObj == null) continue;
                item.LinkedObj.RotateAngle.SetExpression(LinkedPad.ShowRad(item.LinkedObj.RotateAngle.RadValue + angle));
            }
        }
        void flipObj(PointD location, double k)
        {

        }
        void EnableVSRenderer(VisualStudioToolStripExtender.VsVersion version, ThemeBase theme)
        {
            visualStudioToolStripExtender1.SetStyle(menuStrip1, version, theme);
            visualStudioToolStripExtender1.SetStyle(tsPad, version, theme);
            visualStudioToolStripExtender1.SetStyle(statusStrip1, version, theme);
        }

        private void 保存窗口布局ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Directory.CreateDirectory(Flags.LayoutDirectoryPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            InputBoxWindow ib = new InputBoxWindow(Resources.JoinLocalizedString("Save", "Layout"), Resources.Translate("SaveLayoutPrompt"));
            if (ib.ShowDialog() == DialogResult.OK)
            {
                string dest = Flags.LayoutDirectoryPath + "\\" + ib.InputContent + ".config";
                dockPanel1.SaveAsXml(dest);
                ToolStripMenuItem item = new ToolStripMenuItem($"&{'A'.GetNextLetter(加载窗口布局LToolStripMenuItem.DropDownItems.Count)}. {ib.InputContent}", null, LoadLayout_Click) { Tag = dest };
                加载窗口布局LToolStripMenuItem.DropDownItems.Add(item);
            }
        }
        void LoadLayout_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            try
            {
                File.Delete(Flags.DefaultLayoutPath);
                File.Copy(item.Tag as string, Flags.DefaultLayoutPath);
                Flags.SaveLayoutBeforeExit = false;
                MessageBox.Show(Resources.Translate("LoadLayoutComplete"), Resources.Translate("Prompt"), MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {

            }
        }
        //private void 加载窗口布局LToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    OpenFileDialog ofd = new OpenFileDialog()
        //    {
        //        Title = Resources.Translate("Open"),
        //        Filter = $"{Resources.Translate("LayoutFile")}(*.config)|*.config",
        //    };
        //    if (ofd.ShowDialog() == DialogResult.OK)
        //    {
        //        dockPanel1.SuspendLayout(true);
        //        //closeAllContents();
        //        Program.CreateWindows();
        //        try
        //        {
        //            dockPanel1.LoadFromXml(ofd.FileName, Program.GetContentFromPersistString);
        //        }
        //        catch (Exception)
        //        {
        //            MessageBox.Show("Test", Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        }
        //        dockPanel1.ResumeLayout(true, true);
        //    }
        //}
        //void closeAllDocuments()
        //{
        //    if (dockPanel1.DocumentStyle == DocumentStyle.SystemMdi)
        //    {
        //        foreach (Form item in MdiChildren)
        //        {
        //            item.Close();
        //        }
        //    }
        //    else
        //    {
        //        foreach (IDockContent item in dockPanel1.DocumentsToArray())
        //        {
        //            item.DockHandler.DockPanel = null;
        //            item.DockHandler.Close();
        //        }
        //    }
        //}
        //void closeAllContents()
        //{
        //    Program.WinDocuments.DockPanel = null;
        //    Program.WinParameters.DockPanel = null;
        //    Program.WinTools.DockPanel = null;
        //    Program.WinAnimations.DockPanel = null;
        //    Program.WinComponents.DockPanel = null;
        //    Program.WinProperty.DockPanel = null;
        //    //Program.WinRecycleBin.DockPanel = null;
        //    closeAllDocuments();
        //    foreach (FloatWindow item in dockPanel1.FloatWindows)
        //    {
        //        item.Dispose();
        //    }
        //}

        private void tsmiOpen_Click(object sender, EventArgs e)
        {
            Program.WinDocuments.OpenDocuments();
        }

        private void tsmiSave_Click(object sender, EventArgs e)
        {
            Program.WinDocuments.Save();
        }

        private void tsmiSaveAs_Click(object sender, EventArgs e)
        {
            Program.WinDocuments.SaveAs();
        }

        private void 新建动画NToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinAnimations.AddAnimation();
        }

        private void 删除动画DToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinAnimations.DeleteAnimations();
        }

        private void 运动RToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinAnimations.ChangeRunningState(true);
        }

        private void 清空动画ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinAnimations.DeleteAnimations(true);
        }

        private void 停止SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinAnimations.ChangeRunningState(false);
        }

        private void 转向ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinAnimations.Reverse();
        }

        private void 重置持续时间ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.WinAnimations.ResetDuration();
        }

        private void 垂直翻转VToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flipObj(PointD.Empty, 0);
        }

        private void 翻转ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        private void tsmiCloseDocument_Click(object sender, EventArgs e)
        {
            try
            {
                Program.WinDocuments.CloseDocument();
            }
            catch (Exception)
            {

            }
        }

        private void 全屏UToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (LinkedPad == null) return;
            LinkedPad.FullScreenMode = true;
        }

        private void 窗口WToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            WindowsManagerWindow wmw = new WindowsManagerWindow(documentWindows);
            wmw.ShowDialog();
        }
        public void SketchPad_CurrentCoordinateChanged(SketchPad sender, PointD? pt)
        {
            tsslCoordinate.Text = pt == null ? string.Empty : sender.PxyToMath(pt.Value).ToString();
        }
        public void SketchPad_NameChanged(SketchPad sender)
        {
            Text = $"{sender.Document.Title} [{sender.Name}] - {Flags.SoftwareName}{Flags.AdministratorFlag}";
        }
        public void SketchPad_NewCommandAdded(SketchPad sender, ICommand cmd)
        {
            if (sender.IsSelectedPad)
            {
                tsbUndo.Enabled = true;
                tsbUndo.DropDownItems.Insert(0, cmd.UndoMenuItem);
                tsbRedo.DropDownItems.Clear();
                tsbRedo.Enabled = false;
            }
        }
        public void SketchPad_Redid(SketchPad sender, ICommand peek)
        {
            if (sender.IsSelectedPad)
            {
                tsbRedo.DropDownItems.Remove(peek.RedoMenuItem);
                if (tsbRedo.DropDownItems.Count == 0)
                {
                    tsbRedo.Enabled = false;
                }
                tsbUndo.DropDownItems.Insert(0, peek.UndoMenuItem);
                tsbUndo.Enabled = true;
            }
        }
        public void SketchPad_Undid(SketchPad sender, ICommand peek)
        {
            if (sender.IsSelectedPad)
            {
                tsbUndo.DropDownItems.Remove(peek.UndoMenuItem);
                if (tsbUndo.DropDownItems.Count == 0)
                {
                    tsbUndo.Enabled = false;
                }
                tsbRedo.DropDownItems.Insert(0, peek.RedoMenuItem);
                tsbRedo.Enabled = true;
            }
        }
        public void Document_DocumentWindow_DockStateChanged(object sender, EventArgs e)
        {
            DocumentWindow win = sender as DocumentWindow;
            if (win.DockStateBackup == DockState.Unknown && win.DockState == DockState.Hidden) return;
            switch (win.DockState)
            {
                case DockState.Unknown:
                case DockState.Hidden:
                    if (dockPanel1.DocumentsCount == 0)
                    {
                        Program.FreezeDocument();
                        Text = Flags.SoftwareName + Flags.AdministratorFlag;
                    }
                    break;
            }
        }
        public void Document_Activated(Document sender)
        {
            LinkedDocument = sender;
            if (LinkedDocument == null)
            {
                新建参数ToolStripMenuItem.Enabled = 清空参数ToolStripMenuItem.Enabled = false;
            }
            else
            {
                if (Settings.Instance.CloseHomePageAfterDocumentLoaded && welcomeWin != null)
                {
                    welcomeWin.Close();
                    welcomeWin = null;
                }
                DockState ds = LinkedDocument.DocumentWindow.DockState;
                switch (ds)
                {
                    case DockState.Unknown:
                        LinkedDocument.DocumentWindow.Show(dockPanel1, DockState.Document);
                        LinkedDocument.WindowMenuItem.CheckedChanged += windowMenu_CheckedChanged;
                        LinkedDocument.WindowMenuItem.OwnerChanged += windowMenu_OwnerChanged;
                        break;
                    case DockState.Hidden:
                        LinkedDocument.DocumentWindow.DockState = LinkedDocument.DocumentWindow.DockStateBackup;
                        break;
                    default:
                        if (!LinkedDocument.DocumentWindow.IsActivated)
                        {
                            LinkedDocument.DocumentWindow.Activate();
                        }
                        CheckWindowMenu(LinkedDocument.WindowMenuItem);
                        break;
                }
                switch (ds)
                {
                    case DockState.Unknown:
                    case DockState.Hidden:
                        WindowTopMenu.DropDownItems.Insert(WindowTopMenu.DropDownItems.Count - 1, LinkedDocument.WindowMenuItem);
                        documentWindows[LinkedDocument.WindowMenuItem] = LinkedDocument.DocumentWindow;
                        LinkedDocument.WindowMenuItem.Checked = true;
                        break;
                }
                新建参数ToolStripMenuItem.Enabled = 清空参数ToolStripMenuItem.Enabled = true;
            }
        }
        public void CheckWindowMenu(ToolStripMenuItem menu)
        {
            foreach (ToolStripMenuItem item in documentWindows.Keys)
            {
                item.Tag = false;
                item.Checked = item == menu;
                item.Tag = true;
            }
        }
        void windowMenu_OwnerChanged(object sender, EventArgs e)
        {
            ToolStripMenuItem menu = sender as ToolStripMenuItem;
            if (WindowTopMenu.DropDownItems.Contains(menu))
            {
                documentWindows.Add(menu, null);
            }
            else
            {
                documentWindows.Remove(menu);
            }
        }
        void windowMenu_CheckedChanged(object sender, EventArgs e)
        {
            ToolStripMenuItem menu = sender as ToolStripMenuItem;
            if (!(bool)menu.Tag) return;
            if (menu.Checked)
            {
                CheckWindowMenu(menu);
                documentWindows[menu].Activate();
            }
            else
            {
                menu.Tag = false;
                menu.Checked = true;
                menu.Tag = true;
            }
        }
        private void tsbZoomIn_EnabledChanged(object sender, EventArgs e)
        {
            放大IToolStripMenuItem.Enabled = tsbZoomIn.Enabled;
        }

        private void tsbZoomOut_EnabledChanged(object sender, EventArgs e)
        {
            缩小OToolStripMenuItem.Enabled = tsbZoomOut.Enabled;
        }

        private void tsbFullScreen_EnabledChanged(object sender, EventArgs e)
        {
            全屏UToolStripMenuItem.Enabled = tsbFullScreen.Enabled;
        }

        private void tsbMovePad_EnabledChanged(object sender, EventArgs e)
        {
            移动画板ToolStripMenuItem.Enabled = tsbMovePad.Enabled;
        }

        private void tsbMoveObjects_EnabledChanged(object sender, EventArgs e)
        {
            移动对象ToolStripMenuItem.Enabled = tsbMoveObjects.Enabled;
        }

        private void tsbTransformPoint_EnabledChanged(object sender, EventArgs e)
        {
            切换点类型ToolStripMenuItem.Enabled = tsbTransformPoint.Enabled;
        }

        private void tsbCaptureToFile_EnabledChanged(object sender, EventArgs e)
        {
            截图到文件ToolStripMenuItem.Enabled = tsbCaptureToFile.Enabled;
        }

        private void tsbCaptureToClipboard_EnabledChanged(object sender, EventArgs e)
        {
            截图至剪贴板ToolStripMenuItem.Enabled = tsbCaptureToClipboard.Enabled;
        }

        private void 截图到文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            captureToFile();
        }

        private void 截图至剪贴板ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            captureToClipboard();
        }

        private void 放大IToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LinkedPad.ZoomIn(Settings.Instance.ZoomDelta);
        }

        private void 缩小OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LinkedPad.ZoomOut(Settings.Instance.ZoomDelta);
        }

        private void 移动画板ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            tsbMovePad.Checked = 移动画板ToolStripMenuItem.Checked;
        }

        private void 移动对象ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            tsbMoveObjects.Checked = 移动对象ToolStripMenuItem.Checked;
        }

        private void 切换点类型ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            tsbTransformPoint.Checked = 切换点类型ToolStripMenuItem.Checked;
        }

        public void ShowMainStatus(string msg)
        {
            tsslMainStatus.Text = msg;
        }

        public void AppendMainStatus(string msg)
        {
            tsslMainStatus.Text += msg;
        }

        public void ShowSecondaryStatus(string msg)
        {
            tsslSpareStatus.Text = msg;
        }

        public void AppendSecondaryStatus(string msg)
        {
            tsslSpareStatus.Text += msg;
        }

        public void ClearMainStatus()
        {
            tsslMainStatus.Text = string.Empty;
        }

        public void ClearSecondaryStatus()
        {
            tsslSpareStatus.Text = string.Empty;
        }

        private void 查看帮助HToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                WebClient wc = new WebClient();
                string dest = Path.Combine(Flags.TempPath, Guid.NewGuid().ToString());
                wc.DownloadFile(Flags.OfficialWebsite + "/" + Flags.SoftwareName + "/view_help", dest);
                string addr = File.ReadAllText(dest);
                File.Delete(dest);
                Process.Start(addr);
            }
            catch (Exception)
            {
                Process.Start(Flags.OfficialWebsite + "/help.jsp");
            }
        }

        private void 查看示例EToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                WebClient wc = new WebClient();
                string dest = Path.Combine(Flags.TempPath, Guid.NewGuid().ToString());
                wc.DownloadFile(Flags.OfficialWebsite + "/" + Flags.SoftwareName + "/view_demos", dest);
                string addr = File.ReadAllText(dest);
                File.Delete(dest);
                Process.Start(addr);
            }
            catch (Exception)
            {
                Process.Start(Flags.OfficialWebsite + "/demos.jsp");
            }
        }

        private void 重置窗口布局RToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                File.Delete(Flags.DefaultLayoutPath);
                Flags.SaveLayoutBeforeExit = false;
                MessageBox.Show(Resources.Translate("ResetLayoutComplete"), Resources.Translate("Prompt"), MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {

            }
        }
        [Browsable(false)]
        public PageSettings DefaultPageSettings { get; private set; }
        [Browsable(false)]
        public PrinterSettings DefaultPrinterSettings { get; private set; }
        private void tsmiPageSettings_Click(object sender, EventArgs e)
        {
            PageSetupDialog psd = new PageSetupDialog();
            if (psd.ShowDialog() == DialogResult.OK)
            {
                DefaultPageSettings = psd.PageSettings;
                DefaultPrinterSettings = psd.PrinterSettings;
            }
        }

        private void tsmiViewPrint_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog ppd = new PrintPreviewDialog();
            if (ppd.ShowDialog() == DialogResult.OK)
            {

            }
        }

        private void 检查更新UToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string path = Path.Combine(Flags.UpdateDirectoryPath, "Update.exe");
            if (File.Exists(path))
            {
                Process.Start(path);
            }
            else
            {
                MessageBox.Show(Resources.Translate("UpdateProgramNotExist"), Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void MainWindow_DragDrop(object sender, DragEventArgs e)
        {
            //管理员权限下文件拖拽无效
            Array arr = e.Data.GetData(DataFormats.FileDrop) as Array;
            if (arr == null) return;
            Program.WinDocuments.OpenDocuments(arr.OfType<string>());
        }

        private void MainWindow_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
    }
}
